import 'package:flutter/material.dart';

class WSize extends StatefulWidget {
  @override
  _WSizeState createState() => _WSizeState();
}

class _WSizeState extends State<WSize> {
  double pixelRatio = 0.0;
  double screenWidth = 0.0;
  double screenHeight = 0.0;
  double statusBarHeight = 0.0;
  double bottomBarHeight = 0.0;

  final GlobalKey container = GlobalKey();

  double w = 0, h = 0;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  void size() {
    MediaQueryData mq = MediaQuery.of(context);
    // 屏幕密度
    pixelRatio = mq.devicePixelRatio;
    // 屏幕宽(注意是dp, 转换px 需要 screenWidth * pixelRatio)
    screenWidth = mq.size.width;
    // 屏幕高(注意是dp)
    screenHeight = mq.size.height;
    // 顶部状态栏, 随着刘海屏会增高
    statusBarHeight = mq.padding.top;
    // 底部功能栏, 类似于iPhone XR 底部安全区域
    bottomBarHeight = mq.padding.bottom;
  }

  @override
  Widget build(BuildContext context) {
    this.size();
    return Scaffold(
      appBar: AppBar(
        title: Text("尺寸"),
        centerTitle: true,
      ),
      body: Align(
        child: Column(
          children: <Widget>[
            Text("屏幕密度${pixelRatio}"),
            SizedBox(
              height: 10,
            ),
            Text("屏幕宽dp:${screenWidth}"),
            SizedBox(
              height: 10,
            ),
            Text("屏幕高dp:${screenHeight}"),
            SizedBox(
              height: 10,
            ),
            Text("屏幕宽px:${screenWidth * pixelRatio}"),
            SizedBox(
              height: 10,
            ),
            Text("屏幕高px:${screenHeight * pixelRatio}"),
            SizedBox(
              height: 10,
            ),
            Text("顶部状态栏:${statusBarHeight}"),
            SizedBox(
              height: 10,
            ),
            Text("底部功能栏:${bottomBarHeight}"),
            Container(
              key: container,
              height: screenHeight / 2,
              width: screenWidth / 2,
              color: Colors.red,
            ),
            OutlineButton(
              child: Text('获取宽高'),
              onPressed: () {
                _getWH();
              },
            ),
            Text("指定容器宽:${w}, 高 : ${h}"),
          ],
        ),
      ),
    );
  }

  void _getWH() {
    final containerWidth = container.currentContext.size.width;
    final containerHeight = container.currentContext.size.height;
    setState(() {
      w = containerWidth;
      h = containerHeight;
    });
  }
}
